<?php

class ExceptionDB extends Exception {
    
}

class Application_Model_DB {

    protected $db = null;

    function __construct() {
        $this->connect('ExceptionDB');
        return $this;
    }

    protected static $kwem;
    protected static $smsem;
    protected static $swdb_em;
    protected static $emArray = Array();

    function getEntityManager($db_name = 'db') {
        switch ($db_name) {
            case 'db':
                if (null === Super_Model_Admin::$swdb_em) {
                    $em = $this->initEntityManager('db');
                    Super_Model_Admin::$swdb_em = $em;
                } else {
                    $em = Super_Model_Admin::$swdb_em;
                }
                break;
            case 'emailserviceNativeSQL' :
                $em = $this->initConnectServer($db_name);
                break;
        }
        return $em;
    }

    private function initConnectServer($db_name) {
        $zf_config = new Zend_Config_Ini('../application/configs/bd.ini', $db_name);
        return new PDO('mysql:host=' . $zf_config->host . ';dbname=' . $zf_config->dbname . '', $zf_config->login, $zf_config->pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    }

    private function initEntityManager($iniSectionName, $charset = 'utf8', $setNames = 'utf8') {
        if (!(isset(self::$emArray[$iniSectionName][$charset][$setNames])) or null === self::$emArray[$iniSectionName][$charset][$setNames]) {

            require_once 'Doctrine/Common/ClassLoader.php';
            $classLoader = new Doctrine\Common\ClassLoader('Doctrine');
            $classLoader->register();
            $config = new Doctrine\ORM\Configuration();
            $config->setProxyDir('/proxies');
            $config->setProxyNamespace('/proxies');
            $config->setAutoGenerateProxyClasses(TRUE); // APPLICATION_ENV == "development"

            $driverImpl = $config->newDefaultAnnotationDriver("/entity/");
            $config->setMetadataDriverImpl($driverImpl);

            $zf_config = new Zend_Config_Ini('../application/configs/bd.ini', $iniSectionName);
            $conn = array(
                'driver' => 'pdo_mysql',
                'host' => $zf_config->host,
                'user' => $zf_config->login,
                'password' => $zf_config->pass,
                'dbname' => $zf_config->dbname,
                'charset' => $charset,
                'driverOptions' => array(1002 => 'SET NAMES ' . $setNames)
            );

            $evm = new Doctrine\Common\EventManager();

            self::$emArray[$iniSectionName][$charset][$setNames] = \Doctrine\ORM\EntityManager::create($conn, $config, $evm);
        }
        return self::$emArray[$iniSectionName][$charset][$setNames];
    }

    final protected function connect($exceptionObj) {
        $zf_config = new Zend_Config_Ini('../application/configs/bd.ini', 'db');
        $config = array(
            'host' => $zf_config->host,
            'name' => $zf_config->login,
            'password' => $zf_config->pass,
            'dbname' => $zf_config->dbname,
        );
        $this->db = @mysql_pconnect($config['host'], $config['name'], $config['password']);
        if ($this->db === false) {
            throw new $exceptionObj('No connect');
        }
        if (!mysql_select_db($config['dbname'], $this->db)) {
            throw new $exceptionObj('Not find this base');
        }
        mysql_query("SET NAMES 'utf8'");
        mysql_query("SET collation_connection='utf8_general_ci'");
        mysql_query("SET collation_server='utf8_general_ci'");
        mysql_query("SET character_set_client='utf8'");
        mysql_query("SET character_set_connection='utf8'");
        mysql_query("SET character_set_results='utf8'");
        mysql_query("SET character_set_server='utf8'");
        return TRUE;
    }

    public function getAll($sql) {
        if ($this->checkConnect()) {
            $q = mysql_query($sql);
            $i = 0;
            $result = array();
            if (!empty($q)) {
                while ($row = mysql_fetch_assoc($q)) {
                    $result[$i++] = $row;
                }
            }
            return $result;
        }
        return false;
    }

    public function getAssoc($sql) {
        if ($this->checkConnect()) {
            $q = mysql_query($sql);
            $result = array();
            if (!empty($q)) {
                while ($row = mysql_fetch_assoc($q)) {
                    $result[reset($row)] = $row;
                }
            }
            return $result;
        }
        return false;
    }

    public function getRow($sql) {
        if ($this->checkConnect()) {
            $q = mysql_query($sql);
            $result = array();
            if (!empty($q)) {
                $result = mysql_fetch_assoc($q);
            }
            return $result;
        }
        return false;
    }

    public function getOne($sql) {
        if ($this->checkConnect()) {
            $q = mysql_query($sql . ' LIMIT 1', $this->db);
            $result = false;
            if (!empty($q)) {
                $row = mysql_fetch_row($q);
                $result = $row[0];
            }
            return $result;
        }
        return false;
    }

    public function exec($sql) {
        if ($this->checkConnect()) {
            $result = mysql_query($sql);
            if (strpos(strtoupper($sql), 'INSERT') === 0) {
                $result = $this->getOne('SELECT LAST_INSERT_ID()');
            }
            return $result;
        }
        return false;
    }

    protected function checkConnect() {
        $result = false;
        if (!is_null($this->db)) {
            $result = true;
        } else {
            $result = $this->connect('ExceptionDB');
        }
        //  trigger_error("Not connection to the base", E_USER_WARNING);
        return $result;
    }

}